<template>
	<view>
		<!-- 搜索导航栏 -->
		<view class="Search-Navigation">
			<i class="return-icon" @click="goBack"></i>
			<view class="search-box">
				<i class="search-icon"></i>
				<u-input placeholder="请输入内容" border="surround" :clearable="true" v-model="value"
					@input="handleInput"></u-input>
				<i class="camera-icon"></i>
			</view>
			<view class="search-button" @click="addHistory">搜索</view>
		</view>
		<view class="Search-Navigation-backgeound"></view>

		<!-- 搜索内容 -->
		<view v-if="value !== ''" class="Search-content">
			<view v-for="(item, index) in asd" :key="index" class="Search-item"
				@click="searchHistoryItem(item.description)">
				<i class="Search-icon"></i>
				<text class="Search-txt">{{ item.description }}</text>
			</view>
		</view>


		<!-- 历史记录框 -->
		<view class="history-box" :class="{ expanded: showAllHistory }" v-show="showHistoryBox && value === ''">
			<view class="history-background">
				<text class="history-text">历史记录</text>
				<i v-if="!isEditing" class="delete-icon" @click="startEditing"></i>
				<view v-if="isEditing" class="edit-options">
					<text class="delete-all" @click="deleteAllHistory">删除全部</text>
					<text class="finish" @click="finishEditing">完成</text>
				</view>
			</view>
			<view class="history-items">
				<text v-for="(item, index) in sortedHistory" :key="index" class="history-item"
					@click="searchHistoryItem(item)">
					{{ item }}
				</text>
			</view>
			<view v-if="history.length > 3" class="toggle-button" @click="toggleHistory">
				{{ showAllHistory ? "收起" : "显示更多" }}
			</view>
		</view>

		<!-- 猜你想搜部分 -->
		<view class="Guess-you-want-to-search" v-show="value === ''">
			<text class="history-text">猜你想搜</text>
			<i class="eye-icon" @click="toggleGuessContent"></i>
		</view>
		<view class="Guess-you-want-to-search-content" v-show="showGuessContent && value === ''">
			<view v-for="(item, index) in arr" :key="index" class="box" @click="searchGuessItem(item.name)">
				{{ item.name }}
			</view>
		</view>

		<!-- 常用分类 -->
		<view class="hotspot" v-show="value === ''">
			<text class="hotspot-txt">常用分类</text>
		</view>
		<!-- 热点内容 -->
		<view class="Guess-you-want-to-search-content" v-show="value === ''">
			<view v-for="(item, index) in arrey" :key="index" class="box-02" @click="searchGuessItem(item.name)">
				<image :src="item.image" class="Product" />
				<text class="Product-icon">{{ item.name }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				value: "",
				history: [],
				showHistoryBox: false,
				showAllHistory: false,
				isEditing: false,
				showGuessContent: true,
				asd: [],
				arr: [{
						name: "止鼾神器"
					},
					{
						name: "医用修复面膜"
					},
					{
						name: "械字号医用面膜"
					},
					{
						name: "素颜霜"
					},
					{
						name: "面膜医美"
					},
					{
						name: "面膜医用"
					}
				],
				arrey: [{
						image: "../../static/icon/Sunscreen.png",
						name: "防嗮"
					},
					{
						image: "../../static/icon/Eyecream.png",
						name: "眼霜"
					},
					{
						image: "../../static/icon/Eyelash.png",
						name: "眼睫毛"
					},
					{
						image: "../../static/icon/Earclip.png",
						name: "耳夹"
					},
					{
						image: "../../static/icon/tissue.png",
						name: "纸巾"
					},
					{
						image: "../../static/icon/Ring.png",
						name: "戒指"
					},
					{
						image: "../../static/icon/silkstockings.png",
						name: "光腿神器"
					},
					{
						image: "../../static/icon/cosmetic.png",
						name: "美瞳"
					}
				],
			};
		},
		watch: {
			value(newVal) {
				console.log(newVal);
				this.getDataFromBackend();
			}

		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			getDataFromBackend() {
				const jsonData = JSON.stringify({
					keywords: this.value,
					 image: this.asd.image
				});
				if (this.value.trim()) {
					this.request("/product/selectProductsByKeyword", "post", jsonData)
						.then((res) => {
							console.log(res);
							this.asd = res.data.result;
						})
						.catch((err) => {
							console.log(err);
						});
				}
			},
			searchHistoryItem(productName) {
				// 设置搜索框的值为点击的历史记录项
				this.value = productName;
				// 执行搜索
				this.addHistory();
			},

			addHistory() {
			    const trimmedValue = this.value.trim();
			    if (trimmedValue) {
			        this.history.push(trimmedValue); // 允许重复项
			        this.saveHistory();
			        this.showHistoryBox = true;
			        this.history.sort((a, b) => a.length - b.length); // 如果需要，按长度排序
			
			        // 其他清空搜索框并进行API调用的逻辑保持不变
			        const jsonData = JSON.stringify({
			            keywords: trimmedValue
			        });
			        this.value = ""; // 清空搜索框
			
			        this.request("/product/selectProductsByKeyword", "post", jsonData)
			            .then((res) => {
			                console.log(res);
			                this.asd = res.data.result;
			
			                // 根据需要进行导航或其他操作
			                uni.navigateTo({
			                    url: `/pages/searchBox/commodity?data=${encodeURIComponent(JSON.stringify(this.asd))}`
			                });
			            })
			            .catch((err) => {
			                console.log(err);
			            });
			    }
			},

			clearHistory() {
				this.history = [];
				this.saveHistory();
				this.showHistoryBox = false;
				this.isEditing = false;
			},
			toggleHistory() {
				this.showAllHistory = !this.showAllHistory;
			},
			startEditing() {
				this.isEditing = true;
				// this.value = productName;
				this.addHistory();
			},
			deleteAllHistory() {
				this.clearHistory();
			},
			finishEditing() {
				this.isEditing = false;
			},
	
			toggleGuessContent() {
				this.showGuessContent = !this.showGuessContent;
			},
			searchGuessItem(itemName) {
				this.value = itemName;
				this.addHistory();
			},
			handleInput() {
				this.change();
				this.queryBackend();
			},
			change() {
				if (this.value.trim() === '') {
					this.showGuessContent = true; // 显示猜你想搜部分
				} else {
					this.showGuessContent = false; // 隐藏猜你想搜部分
				}
			},
			queryBackend() {
			},
			saveHistory() {
				uni.setStorageSync('searchHistory', this.history);
			},
			loadHistory() {
				const savedHistory = uni.getStorageSync('searchHistory');
				if (savedHistory) {
					this.history = savedHistory;
					this.showHistoryBox = this.history.length > 0;
				}
			}
		},
		computed: {
			sortedHistory() {
				return this.history.sort((a, b) => a.length - b.length);
			}
		},
		onLoad() {
			this.loadHistory();
		}
	};
</script>


<style>
	.Search-Navigation {
		width: 100%;
		height: 100rpx;
		display: flex;
		border-bottom: 1rpx solid gainsboro;
		position: fixed;
		top: 0rpx;
		background-color: white;
		z-index: 1;
	}

	.Search-Navigation-backgeound {
		width: 100%;
		height: 100rpx;
		background-color: antiquewhite;
	}

	.return-icon {
		display: block;
		width: 65rpx;
		height: 65rpx;
		margin: 17rpx 20rpx;
		background-image: url("../../static/icon/retuen.png");
		background-repeat: no-repeat;
		background-size: cover;
	}

	.search-box {
		width: 550rpx;
		height: 70rpx;
		background-color: rgb(244, 244, 244);
		margin-top: 17rpx;
		border-radius: 30rpx;
		display: flex;
	}

	.search-button {
		width: 100rpx;
		height: 65rpx;
		margin-top: 17rpx;
		text-align: center;
		line-height: 65rpx;
		color: darkgrey;
		cursor: pointer;
	}

	.search-icon,
	.camera-icon {
		display: block;
		width: 50rpx;
		height: 50rpx;
		margin-left: 10rpx;
		border-radius: 30rpx;
		background-image: url("../../static/icon/search.png");
		background-repeat: no-repeat;
		margin-top: 10rpx;
		background-size: cover;
	}

	.camera-icon {
		background-image: url("../../static/icon/camera.png");
	}

	.delete-icon {
		display: block;
		width: 50rpx;
		height: 50rpx;
		margin-top: 13rpx;
		margin-right: 15rpx;
		background-image: url("../../static/icon/delete.png");
		background-repeat: no-repeat;
		background-size: cover;
		cursor: pointer;
	}

	.history-box {
		padding: 10rpx;
		width: 700rpx;
		background-color: white;
		margin: auto;
		overflow: hidden;
		transition: height 0.3s ease;
	}

	.history-box.expanded {
		height: auto;
	}

	.history-background {
		width: 100%;
		height: 80rpx;
		display: flex;
		justify-content: space-between;
	}

	.history-text {
		line-height: 80rpx;
		font-weight: bold;
	}

	.edit-options {
		display: flex;
		align-items: center;
	}

	.delete-all,
	.finish {
		margin-right: 10rpx;
		cursor: pointer;
		color: gray;
		font-weight: bold;
	}

	.finish {
		color: black;
	}

	.history-items {
		max-height: 200rpx;
		overflow: hidden;
	}

	.history-box.expanded .history-items {
		max-height: none;
	}

	.history-item {
		display: inline-block;
		margin-top: 20rpx;
		padding: 10rpx;
		border-radius: 28rpx;
		margin-left: 30rpx;
		border: 1rpx solid gainsboro;
	}

	.toggle-button {
		text-align: center;
		margin-top: 20rpx;
		color: blue;
		cursor: pointer;
	}

	.Guess-you-want-to-search {
		width: 700rpx;
		margin: auto;
		display: flex;
		justify-content: space-between;
	}

	.eye-icon {
		display: block;
		width: 45rpx;
		height: 45rpx;
		margin-top: 18rpx;
		background-image: url("../../static/icon/Small eyes.png");
		background-repeat: no-repeat;
		background-size: cover;
		cursor: pointer;
	}

	.Guess-you-want-to-search-content {
		width: 700rpx;
		display: flex;
		margin: auto;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.box {
		width: 340rpx;
		height: 80rpx;
		margin-top: 20rpx;
		line-height: 80rpx;
	}

	.box-02 {
		width: 150rpx;
		height: 150rpx;
		margin-top: 20rpx;
		line-height: 80rpx;
	}

	.Product {
		display: block;
		width: 90rpx;
		height: 90rpx;
		background-color: #f6f6f8;
		margin: auto;
		border-radius: 50%;
	}

	.Product-icon {
		display: block;
		text-align: center;
	}

	.hotspot {
		width: 250rpx;
		height: 80rpx;
		margin-left: 20rpx;
		display: flex;
		justify-content: space-between;
	}

	.hotspot-txt {
		line-height: 80rpx;
		font-size: 35rpx;
		color: black;
		font-weight: bold;
	}

	.Search-item {
		width: 100%;
		height: 100rpx;
		border-bottom: 1rpx solid gainsboro;
		line-height: 100rpx;
		display: flex;
	}

	.Search-icon {
		display: block;
		width: 50rpx;
		height: 50rpx;
		margin-top: 26rpx;
		background-image: url("../../static/icon/search.png");
		background-repeat: no-repeat;
		background-size: cover;
	}

	.Search-txt {
		margin-left: 20rpx;
	}
</style>